package com.example.springbooti18.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 国际化控制器
 */
@RestController
public class I18nController {

    @Autowired
    private MessageSource messageSource;

    /**
     * 获取国际化消息示例
     * 可以通过请求参数 lang 切换语言，例如：/i18n/message?lang=en_US 或 /i18n/message?lang=zh_CN
     */
    @GetMapping("/i18n/message")
    public Map<String, String> getI18nMessage() {
        // 获取当前语言环境
        Locale locale = LocaleContextHolder.getLocale();
        
        // 使用 MessageSource 获取国际化消息
        String welcomeMessage = messageSource.getMessage("welcome.message", null, locale);
        String greetingMessage = messageSource.getMessage("greeting.message", new Object[]{"User"}, locale);
        String currentLanguage = messageSource.getMessage("current.language", new Object[]{locale.getDisplayLanguage(locale)}, locale);
        
        Map<String, String> response = new HashMap<>();
        response.put("welcomeMessage", welcomeMessage);
        response.put("greetingMessage", greetingMessage);
        response.put("currentLanguage", currentLanguage);
        response.put("languageCode", locale.toString());
        
        return response;
    }

    /**
     * 切换语言示例
     * 重定向到消息接口，展示切换后的效果
     */
    @GetMapping("/i18n/change-lang")
    public Map<String, String> changeLanguage(String lang) {
        Map<String, String> response = new HashMap<>();
        if (lang != null && !lang.isEmpty()) {
            response.put("message", "Language will be changed to: " + lang);
            response.put("redirectUrl", "/i18n/message?lang=" + lang);
        } else {
            response.put("error", "Language parameter is required");
        }
        return response;
    }

    /**
     * 列出所有支持的语言
     */
    @GetMapping("/i18n/languages")
    public Map<String, Object> getSupportedLanguages() {
        Locale currentLocale = LocaleContextHolder.getLocale();
        String supportedLanguagesText = messageSource.getMessage("supported.languages", null, currentLocale);
        
        Map<String, Object> response = new HashMap<>();
        response.put("supportedLanguagesText", supportedLanguagesText);
        response.put("availableLanguages", new String[]{"zh_CN", "en_US"});
        response.put("currentLanguage", currentLocale.toString());
        
        // 提供测试链接
        Map<String, String> testLinks = new HashMap<>();
        testLinks.put("中文测试", "/i18n/message?lang=zh_CN");
        testLinks.put("English Test", "/i18n/message?lang=en_US");
        response.put("testLinks", testLinks);
        
        return response;
    }
}